import 'dart:convert';

import 'package:get/get.dart';
import 'package:oi_ai_tool/config/ai_source.dart';
import 'package:oi_ai_tool/config/api_config.dart';
import 'package:oi_ai_tool/model/accesstoken.dart';
import 'package:oi_ai_tool/model/request_token.dart';
import 'package:oi_ai_tool/util/http/http_request.dart';
import 'package:oi_ai_tool/util/http/oi_response.dart';
import 'package:oi_ai_tool/util/storage.dart';
import 'package:oi_ai_tool/util/string_extention.dart';

class UserService extends GetxService {
  String token = "1111";
  @override
  onReady() {
    initTokenData();
  }

  initTokenData() async {
    var tokenData = await OiStorage.get(StoreageKey.TOKEN_KEY);
    var accesstokenData = await OiStorage.get(StoreageKey.ACCESS_KEY);
    if (tokenData != null) {
      RequestToken reqToken =
          RequestToken.formJson(jsonDecode(tokenData ?? ""));

      if (reqToken.aiSource != null &&
          reqToken.aiSource!.isNotEmpty) {
        if (AiSource.BAIDU.type.isEq(reqToken.aiSource!)) {
          baiduToken(reqToken);
        } else if (AiSource.CHATGPT.type.isEq(reqToken.aiSource!)) {}
      }
    }
    if (accesstokenData != null) {
      AccessToken accessToken =
          AccessToken.formJson(jsonDecode(accesstokenData ?? ""));
      if (accessToken.access_token != null) {
        token = accessToken.access_token!;
      }
        }
  }

  baiduToken(RequestToken reqToken) async {
    CommonResult result =
        await OiHttpRequest().post(ApiConfiguration.baiduApiToken, params: {
      "grant_type": reqToken.grantType,
      "client_id": reqToken.apiKey,
      "client_secret": reqToken.secretKey
    });
    _setAndSaveRespData(result);
  }

  void _setAndSaveRespData(CommonResult result) {
    var data = result.data as Map<String, dynamic>;

    AccessToken accessToken = AccessToken.formJson(data);
    OiStorage.set(StoreageKey.ACCESS_KEY, jsonEncode(accessToken));
    token = accessToken.access_token!;
  }
}
